const fragment = document.createDocumentFragment();

class audioMedia {
	constructor(handle) {
		this.media = document.createElement('audio');
		fragment.append(this.media);
		if (typeof handle === 'function') {
			if (fragment && this.media && fragment.hasChildNodes(this.media)) {
				handle({ state: true, msg: '' });
			} else {
				handle({ 
					state: false, 
					msg: `Fragment: ${fragment ? 'exist' : 'lose'}, Media: ${this.media ? 'exist' : 'lose'}, inset: ${fragment.hasChildNodes(this.media)}`
				})
			}
		}
	}
	
	play() {
		if (this.media.paused) {
			this.media.play();
		}
	}
	
	pause() {
		if (!this.media.paused) {
			this.media.pause();
		}
	}
	
	setAttr(attrArr) {
		if (Array.isArray(attrArr) && this.media) {
			attrArr.forEach(item => {
				const [ attr, val ] = item;
				switch(attr) {
					case 'src':
					case 'preload':
						if (typeof val === 'string') {
							this.media[attr] = val;
						}
						break;
					case 'rate':
						if (!isNaN(Number(val)) && val >= 0) {
							this.media.playbackRate = val;
						}
						break;
					case 'volume':
						if (!isNaN(Number(val)) && val >= 0 && val <= 100) {
							this.media.volume = val / 100;
						}
						break;
					case 'muted':
						if (typeof val === 'boolean') {
							this.media.muted = val;
						}
						break;
					case 'time':
						if (!isNaN(Number(val)) && val >= 0) {
							this.media.currentTime = val;
						}
					default: break;
				}
			})
		}
	}
	
	getAttr(attrArr) {
		let data = {};
		if (Array.isArray(attrArr) && this.media) {
			attrArr.forEach(item => {
				data[item] = this.media[item];
			})
		}
		return data;
	}
	
	bindEvent(eventArr) {
		if (Array.isArray(eventArr) && this.media) {
			eventArr.forEach(item => {
				const [event, fn] = item
				if (typeof fn === 'function') {
					this.media.addEventListener(event, fn, false);
				}
			})
		}
	}
	
	buffer() {
		const { buffered, currentTime } = this.media;
		for (let range = 0; range < buffered.length; range++) {
		  if ( currentTime >= buffered.start(range) && currentTime <= buffered.end(range) ) {
				return buffered.end(range) - currentTime;
		  }
		}
	}
}

export default audioMedia;